/*
 *   Copyright (c) 2010 Sonrisa Informatikai Kft. All Rights Reserved.
 * 
 *  This software is the confidential and proprietary information of
 *  Sonrisa Informatikai Kft. ("Confidential Information").
 *  You shall not disclose such Confidential Information and shall use it only in
 *  accordance with the terms of the license agreement you entered into
 *  with Sonrisa.
 * 
 *  SONRISA MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF
 *  THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
 *  TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
 *  PARTICULAR PURPOSE, OR NON-INFRINGEMENT. SONRISA SHALL NOT BE LIABLE FOR
 *  ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR
 *  DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
 */

package com.zh.tree;

import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import javax.swing.tree.DefaultMutableTreeNode;

/**
 *
 * @author Golyo
 */
public class TreeUtils {
    public static <T extends NestedUserObject> DefaultMutableTreeNode buildTree(List<T> treeItems) {
        DefaultMutableTreeNode ret = new DefaultMutableTreeNode();
        return null;
    }

    public static <T extends NestedUserObject> DefaultMutableTreeNode buildOrderedNestedTree(List<T> treeItems) {
        DefaultMutableTreeNode root = new DefaultMutableTreeNode();
        if (!treeItems.isEmpty()) {
            Iterator<T> iterator = treeItems.iterator();
            root.setUserObject(iterator.next());
            buildOreredActual(root, iterator);
        }
        return root;
    }

    public static void setNestedIds(DefaultMutableTreeNode treeNode) {
        setNestedIds(treeNode, 0);
    }


    private static <T extends NestedUserObject>  void buildOreredActual(DefaultMutableTreeNode node, Iterator<T> iterator) {
        if (iterator.hasNext()) {
            DefaultMutableTreeNode pNode = node;
            NestedUserObject act = (NestedUserObject)pNode.getUserObject();
            NestedUserObject obj = iterator.next();
            while (act.getNestedEnd() < obj.getNestedStart()) {
                pNode = (DefaultMutableTreeNode)pNode.getParent();
                act = (NestedUserObject)pNode.getUserObject();
            }
            DefaultMutableTreeNode actNode = new DefaultMutableTreeNode(obj);
            pNode.add(actNode);
            buildOreredActual(actNode, iterator);
        }
    }
    private static int setNestedIds(DefaultMutableTreeNode treeNode, int actNested) {
        Enumeration<DefaultMutableTreeNode> children = treeNode.children();
        NestedUserObject actObject = (NestedUserObject)treeNode.getUserObject();
        actObject.setNestedStart(actNested);
        int ret = actNested;
        while (children.hasMoreElements()) {
            DefaultMutableTreeNode node = children.nextElement();
            ret = setNestedIds(node, ret+1);
        }
        actObject.setNestedEnd(ret);
        return ret;
    }
}
